#!/bin/sh

usage () {
	cat <<EOF>&2
Usage: ${0##*/} SOURCE TARGET

Synchronize all the snapshots in the SOURCE/.snapshots to TARGET/.snapshots.

EOF
}

if [ $# -ne 2 ]; then
	usage
	exit 1
fi

SOURCE="$1"
TARGET="$2"

for i in "$SOURCE"/.snapshots/*; do
	parent=""
	target_i="$TARGET/.snapshots/$(basename "$i")"
	for j in "$i"/*; do
		if [ ! -e "$target_i/$(basename "$j")" ]; then
			if [ -z "$parent" ] ; then
				echo "Sending '$j' to '$target_i'..."
				sudo btrfs send "$j" | sudo btrfs receive "$target_i"
			else
				echo "Sending '$j' to '$target_i' with parent '$parent'..."
				sudo btrfs send -p "$parent" "$j" | sudo btrfs receive "$target_i"
			fi
		fi
		parent="$j"
	done
	## Unset parent for next "i" subvolume.
	parent=""
done
